import { http } from '../utils/http'
import AsyncStorage from "@react-native-async-storage/async-storage";
import now = jest.now;
import dayjs from "dayjs";

/**
 * 流程实例接口
 */
export interface ProcessInstanceVO {
    id: number
    name: string
    processDefinitionId: string
    category: string
    result: number
    tasks: Task[]
    fields: string[]
    status: number
    remark: string
    businessKey: string
    createTime: string
    endTime: string
    startUser?: User
}

/**
 * 任务接口
 */
export interface Task {
    id: string
    name: string
}

/**
 * 用户信息接口
 */
export interface User {
    id: number
    nickname: string
    avatar: string
}

/**
 * 审批任务信息接口
 */
export interface ApprovalTaskInfo {
    id: number
    ownerUser: User
    assigneeUser: User
    status: number
    reason: string
    signPicUrl: string
    createTime: string
    endTime: string
}

/**
 * 审批节点信息接口
 */
export interface ApprovalNodeInfo {
    id: number
    name: string
    nodeType: number
    candidateStrategy?: number
    status: number
    startTime?: string
    endTime?: string
    candidateUsers?: User[]
    tasks: ApprovalTaskInfo[]
}

/**
 * API 响应包装接口
 */
export interface ApiResponse<T = any> {
    code: number
    data: T
    msg?: string
}

/**
 * 流程实例 API
 */
export const ProcessInstanceApi = {
    /**
     * 获取流程实例详情
     * @param id 流程实例ID
     * @returns 流程实例详情
     */
    getProcessInstance: (id: string): Promise<ApiResponse<ProcessInstanceVO>> => {
        return http.get(`/bpm/process-instance/get?id=${id}`)
    },

    /**
     * 获取审批详情
     * @param params 查询参数
     * @returns 审批详情
     */
    getApprovalDetail: (params: any): Promise<ApiResponse<ApprovalNodeInfo[]>> => {
        return http.get(`/bpm/process-instance/get-approval-detail?processInstanceId=${params.processInstanceId}`)
    },

    /**
     * 获取下一个执行的流程节点
     * @param params 查询参数
     * @returns 下一个流程节点
     */
    getNextApprovalNodes: (params: any): Promise<ApiResponse<any>> => {
        return http.get('/bpm/process-instance/get-next-approval-nodes', { params })
    },

    /**
     * 获取流程实例BPMN模型视图
     * @param id 流程实例ID
     * @returns BPMN模型视图
     */
    getProcessInstanceBpmnModelView: (id: string): Promise<ApiResponse<any>> => {
        return http.get(`/bpm/process-instance/get-bpmn-model-view?id=${id}`)
    },

    /**
     * 发起人取消流程实例
     * @param processInstanceId 流程实例ID
     * @param reason 取消原因
     * @returns 取消结果
     */
    cancelProcessInstanceByStartUser: async (processInstanceId: string, reason: string) => {
        return await http.delete('/bpm/process-instance/cancel-by-start-user', {
            data: {
                id: processInstanceId, 
                reason: reason
            }
        })
    },
}

// 审批相关API
export const TaskApi = {
    // 审批通过
    approveTask: async (data: { id: string; reason: string }) => {
        const userinfo = JSON.parse(<string>await AsyncStorage.getItem("userInfo"));
        data.reason += `          ——${userinfo.nickname}   ${dayjs().format("YYYY年M月D日")}`
        return await http.put('/bpm/task/approve', data)
    },

    // 审批拒绝
    rejectTask: async (data: { id: string; reason: string }) => {
        const userinfo = JSON.parse(<string>await AsyncStorage.getItem("userInfo"));
        data.reason += `          ——${userinfo.nickname}   ${dayjs().format("YYYY年M月D日")}`
        return await http.put('/bpm/task/reject', data)
    },

    // 获取任务详情
    getTaskDetail: async (taskId: string) => {
        return await http.get(`/bpm/task/get?id=${taskId}`)
    },
}

/**
 * 任务状态枚举
 */
export enum TaskStatus {
    NOT_START = 0,      // 未开始
    IN_PROGRESS = 1,    // 进行中
    COMPLETED = 2,      // 已完成
    REJECTED = 3,       // 已拒绝
    CANCELLED = 4,      // 已取消
}

/**
 * 节点类型枚举
 */
export enum NodeType {
    START_NODE = 1,           // 开始节点
    END_NODE = 2,             // 结束节点
    USER_TASK_NODE = 3,       // 用户任务节点
    SERVICE_TASK_NODE = 4,    // 服务任务节点
    GATEWAY_NODE = 5,         // 网关节点
    SUBPROCESS_NODE = 6,      // 子流程节点
    CHILD_PROCESS_NODE = 7,   // 子流程节点
}

/**
 * 候选策略枚举
 */
export enum CandidateStrategy {
    NONE = 0,                    // 无
    START_USER_SELECT = 1,       // 发起人选择
    APPROVE_USER_SELECT = 2,     // 审批人选择
    FIXED_USERS = 3,            // 固定用户
    ROLE_USERS = 4,             // 角色用户
    DEPT_USERS = 5,             // 部门用户
}
